package com.micro.school.order.service.impl;

import com.micro.school.common.core.context.SecurityContextHolder;
import com.micro.school.common.core.domain.R;
import com.micro.school.order.entity.*;
import com.micro.school.order.mapper.*;
import com.micro.school.order.service.PayOrderImportRecordService;
import com.micro.school.order.util.OrderNoGenerator;
import com.micro.school.order.vo.PayStudentFeeVo;
import com.micro.school.system.api.RemoteEduService;
import com.micro.school.system.api.domain.vo.SchoolCampusVos;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("PayOrderImportRecordServiceImpl")
public class PayOrderImportRecordServiceImpl implements PayOrderImportRecordService {

    @Resource
    private PayOrderImportRecordMapper payOrderImportRecordMapper;

    @Resource
    private PayStudentFeeMapper payStudentFeeMapper;

    @Resource
    private PayStudentFeeItemMapper payStudentFeeItemMapper;

    @Resource
    private PayFeeItemConfigMapper payFeeItemConfigMapper;

    @Autowired
    private RemoteEduService eduService;

    @Override
    public String insertPayOrderImportRecord(List<PayOrderImportRecord> uploadVos, PayOrderImport payOrderImport) {
        StringBuffer stringBuffer = new StringBuffer();
        int insertOrUpdateBatch = payOrderImportRecordMapper.insertOrUpdateBatch(uploadVos);
        if (insertOrUpdateBatch > 0 && payOrderImport.getImportStatus() == 10){
            // 按学生姓名分组处理
            Map<String, List<PayOrderImportRecord>> recordsByStudent = uploadVos.stream()
                    .collect(Collectors.groupingBy(PayOrderImportRecord::getStudentName));
            Map<Long,String> campusMap = new HashMap<>();
            // 遍历每个学生组
            for (Map.Entry<String, List<PayOrderImportRecord>> entry : recordsByStudent.entrySet()) {
                String studentName = entry.getKey();
                String generateOrderNo = OrderNoGenerator.generateOrderNo();
                List<PayOrderImportRecord> studentRecords = entry.getValue();
                // 使用第一个记录作为学生基本信息来源
                PayOrderImportRecord firstRecord = studentRecords.get(0);

                PayStudentFee payStudentFees = new PayStudentFee();
                payStudentFees.setStudentName(firstRecord.getStudentName());
                payStudentFees.setIdNumber(firstRecord.getIdNumber());
                payStudentFees.setFeeYear(firstRecord.getFeeYear());
                payStudentFees.setFeeYearId(firstRecord.getFeeYearId());
                payStudentFees.setTenantId(Integer.valueOf(SecurityContextHolder.getUserTenantId()));
                List<PayStudentFeeVo> payStudentFeeVos = payStudentFeeMapper.selectNoPayStudent(payStudentFees);
                if (payStudentFeeVos != null && payStudentFeeVos.size() > 0){
                    //如果没有支付就直接替换掉
                    payStudentFeeMapper.deleteById(payStudentFeeVos.get(0).getId());
                    payStudentFeeItemMapper.deleteByStudentFeeId(Long.valueOf(payStudentFeeVos.get(0).getId()));
                }
                // 创建学生收费主表记录
                PayStudentFee payStudentFee = new PayStudentFee();
                // 填充学生基本信息
                payStudentFee.setBillNo(generateOrderNo);
                payStudentFee.setStudentName(firstRecord.getStudentName());
                payStudentFee.setIdNumber(firstRecord.getIdNumber());
                if (firstRecord.getStudentId() != null) {
                    payStudentFee.setStudentId(firstRecord.getStudentId().intValue());
                    payStudentFee.setStudyPeriod(firstRecord.getSchoolSystem());
                }
                // 校区信息
                payStudentFee.setCampusId(firstRecord.getCampusId());
                fillCampusName(firstRecord.getCampusId(),campusMap,payStudentFee);
                // 学院信息
                if (firstRecord.getCollegeId() != null && !firstRecord.getCollegeId().isEmpty()) {
                    try {
                        payStudentFee.setCollegeId(Long.valueOf(firstRecord.getCollegeId()));
                    } catch (NumberFormatException e) {
                        // 记录转换异常
                    }
                }
                payStudentFee.setCollegeName(firstRecord.getCollegeName());
                // 模式信息
                if (firstRecord.getModelId() != null && !firstRecord.getModelId().isEmpty()) {
                    try {
                        payStudentFee.setModelId(Long.valueOf(firstRecord.getModelId()));
                    } catch (NumberFormatException e) {
                        // 记录转换异常
                    }
                }
                payStudentFee.setModelName(firstRecord.getModelName());
                // 专业信息
                if (firstRecord.getMajorId() != null && !firstRecord.getMajorId().isEmpty()) {
                    try {
                        payStudentFee.setMajorId(Long.valueOf(firstRecord.getMajorId()));
                    } catch (NumberFormatException e) {
                        // 记录转换异常
                    }
                }
                payStudentFee.setMajorName(firstRecord.getMajorName());
                // 年级信息
                if (firstRecord.getGradeId() != null && !firstRecord.getGradeId().isEmpty()) {
                    try {
                        payStudentFee.setGradeId(Long.valueOf(firstRecord.getGradeId()));
                    } catch (NumberFormatException e) {
                        // 记录转换异常
                    }
                }
                payStudentFee.setGradeName(firstRecord.getGradeName());
                // 学年信息
                payStudentFee.setFeeYearId(firstRecord.getFeeYearId());
                payStudentFee.setFeeYear(firstRecord.getFeeYear());
                // 计算该学生的总金额（合并所有收费项目）
                double totalAmount = studentRecords.stream()
                        .mapToDouble(record -> record.getItemPrice() != null ?
                                record.getItemPrice().doubleValue() : 0.0)
                        .sum();
                payStudentFee.setAmountPayable(totalAmount);
                payStudentFee.setAmountPending(totalAmount);
                payStudentFee.setAmountPaid(0.0);
                payStudentFee.setAmountRefunded(0.0);

                payStudentFee.setAmountDeducted(0.0);
                // 状态信息
                payStudentFee.setBillStatus(10); // 默认未支付状态
                // 租户信息
                payStudentFee.setTenantId(Integer.valueOf(SecurityContextHolder.getUserTenantId()));
                // 删除标记
                payStudentFee.setDeleteFlag(firstRecord.getDeleteFlag());
                // 创建信息
                payStudentFee.setCreateDept(firstRecord.getCreateDept());
                payStudentFee.setCreateBy(firstRecord.getCreateBy());
                payStudentFee.setCreateTime(new Date());
                payStudentFee.setUpdateBy(firstRecord.getCreateBy());
                payStudentFee.setUpdateTime(new Date());
                payStudentFee.setRefundStatus(10);
                payStudentFee.setCloseStatus("1");
                payStudentFee.setCancelStatus(1);
                // 保存学生收费主表记录
                payStudentFeeMapper.insert(payStudentFee);
                // 为该学生的所有收费记录创建明细项
                for (PayOrderImportRecord record : studentRecords) {
                    PayStudentFeeItem payStudentFeeItem = new PayStudentFeeItem();
                    // 关联主表ID
                    payStudentFeeItem.setStudentFeeId(payStudentFee.getId());
                    payStudentFeeItem.setBillNo(generateOrderNo);
                    // 收费项目配置信息
                    if (record.getFeeItemConfigName() != null && !record.getFeeItemConfigName().isEmpty()) {
                        PayFeeItemConfig payFeeItemConfig = new PayFeeItemConfig();
                        payFeeItemConfig.setItemName(record.getFeeItemConfigName());
                        payFeeItemConfig.setTenantId(Integer.valueOf(SecurityContextHolder.getUserTenantId()));
                        List<PayFeeItemConfig> payFeeItemConfigs = payFeeItemConfigMapper.selectPayFeeItemConfigList(payFeeItemConfig);
                        if (!payFeeItemConfigs.isEmpty()) {
                            payStudentFeeItem.setFeeItemConfigId(payFeeItemConfigs.get(0).getId().intValue());
                        }
                        payStudentFeeItem.setFeeItemConfigName(record.getFeeItemConfigName());
                    }

                    // 单价
                    if (record.getItemPrice() != null) {
                        payStudentFeeItem.setItemPrice(record.getItemPrice().doubleValue());
                    }
                    // 数量，默认为1
                    payStudentFeeItem.setItemQuantity(1);
                    // 小计金额
                    if (record.getItemPrice() != null) {
                        payStudentFeeItem.setTotalAmount(record.getItemPrice().doubleValue());
                    }
                    // 显示顺序
                    payStudentFeeItem.setOrderNum(0);
                    // 支付状态
                    payStudentFeeItem.setPayStatus(10); // 待支付
                    // 租户ID
                    payStudentFeeItem.setTenantId(Integer.valueOf(SecurityContextHolder.getUserTenantId()));
                    // 删除标记
                    payStudentFeeItem.setDeleteFlag("0");
                    // 创建部门
                    payStudentFeeItem.setCreateDept(record.getCreateDept());
                    // 创建者
                    payStudentFeeItem.setCreateBy(record.getCreateBy());
                    // 创建时间
                    payStudentFeeItem.setCreateTime(new Date());
                    // 更新者
                    payStudentFeeItem.setUpdateBy(record.getCreateBy());
                    // 更新时间
                    payStudentFeeItem.setUpdateTime(new Date());

                    payStudentFeeItem.setFeeItemConfigType(record.getFeeItemConfigType());

                    payStudentFeeItem.setMandatoryStatus(record.getMandatoryStatus());
                    // 保存学生收费明细记录
                    payStudentFeeItemMapper.insert(payStudentFeeItem);
                }
            }
            stringBuffer.append("");
        } else {
            stringBuffer.append("导入失败！");
        }
        return stringBuffer.toString();
    }

    private void fillCampusName(Long campusId,Map<Long,String> campusMap,PayStudentFee payStudentFee){
        if(campusMap.containsKey(campusId)){
            payStudentFee.setCampusName(campusMap.get(campusId));
            return;
        }
        //设置名字
        if(null!=campusId){
            R<SchoolCampusVos> beanR = eduService.getCampusById(campusId);
            if(null!=beanR && null!=beanR.getData()){
                SchoolCampusVos bean = beanR.getData();
                if(null!=bean){
                    payStudentFee.setCampusName(bean.getCampusName());
                    campusMap.put(campusId,bean.getCampusName());
                }
            }
        }
    }

    @Override
    public List<PayOrderImportRecord> selectPayOrderImportRecordList(PayOrderImportRecord payOrderImportRecord) {
        List<PayOrderImportRecord> payOrderImportRecordList = payOrderImportRecordMapper.queryAllByLimit(payOrderImportRecord);
        if (1 == SecurityContextHolder.getUserIdcardState()){
            payOrderImportRecordList.forEach(vo -> {
                if (vo.getIdNumber() != null && vo.getIdNumber().length() > 8) {
                    String maskedIdNumber = vo.getIdNumber().substring(0, vo.getIdNumber().length() - 8) + "********";
                    vo.setIdNumber(maskedIdNumber);
                } else if (vo.getIdNumber() != null) {
                    vo.setIdNumber(vo.getIdNumber().replaceAll(".", "*"));
                }
            });
        }

        return payOrderImportRecordList;
    }

    @Override
    public int remove(Long ids) {
        return payOrderImportRecordMapper.remove(ids, Integer.parseInt(SecurityContextHolder.getUserTenantId()));
    }

    @Override
    public Map<String, Object> listMessage(PayOrderImportRecord payOrderImportRecord) {
        Map<String, Object> map = payOrderImportRecordMapper.listMessage(payOrderImportRecord);
        List<PayOrderImportRecord> mapDetail = payOrderImportRecordMapper.listMessageDetail(payOrderImportRecord);
        map.put("detail", mapDetail);
        return map;
    }
}
